﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace Kinect
{
    public class BlobProcessor
    {
       
        Point p = new Point();
        int count = 0;
        Dictionary<System.Windows.Point, int> positions = new Dictionary<System.Windows.Point, int>();
        int width = 640;
        int height = 480;
        short[] array = new short[640 * 480];

        int thresholdMin = 800;
        int thresholdMax = 900;

        public BlobProcessor()
        {

        }

        public  Dictionary<System.Windows.Point, int> Process(short[] pixels)
        {
            pixels.CopyTo(array, 0);

            Process();

            return positions;
        }

        private void Process()
        {
            positions = new Dictionary<System.Windows.Point, int>();

            for (int x = 0; x < width; x += 10)
            {
                for (int y = 0; y < height; y += 10)
                {
                    if (array[y * width + x] < thresholdMin || array[y * width + x] > thresholdMax)
                    {
                        continue;
                    }

                    p.X = 0;
                    p.Y = 0;
                    count = 0;

                    startY = y;

                    FillWithArray(x, y);

                    p.X /= count;
                    p.Y /= count;

                    if (count > 1000)
                    {
                        positions.Add(p, count);
                    }
                }
            }
        }

        int startX, startY;

        private void FillWithArray(int x, int y)
        {
            if (array[y * width + x] < thresholdMin || array[y * width + x] > thresholdMax)
            {
                return;
            }

            if (x < 0)
            {
                return;
            }

            if (y < 0)
            {
                return;
            }

            if (y >= height)
            {
                return;
            }

            if (x >= width)
            {
                return;
            }

            if (count > 9000)
            {
                return;
            }

            if (y - startY > 50)
            {
                return;
            }

            p.X += x;
            p.Y += y;

            count++;

            array[y * width + x] = 0;

            FillWithArray(x + 1, y);
            FillWithArray(x, y + 1);
            FillWithArray(x - 1, y);
            FillWithArray(x, y - 1);

        }
    }


}
